<template>
  <div>
    <NavBar></NavBar>
    <div class="body">
      <div class="container">
        <div class="content-head">
          <div class="bg-head"></div>
          <div class="msg-head">
            <div class="avatar-body">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
            <div class="user-msg">
              <p class="user-name">{{userName}}</p>
              <p>
                <span>{{age}}岁</span>&nbsp;&nbsp;
                <span>
                  <el-tag type="primary" v-if="sex == 0"><i class="el-icon-male"></i></el-tag>
                  <el-tag type="danger" v-if="sex == 1"><i class="el-icon-female"></i></el-tag>
                </span>
              </p>
            </div>
            <div class="edit-data">
              <span v-if="isFollow">
                <el-button plain type="success" @click="unFollowUser($route.query.id)">
                    已关注
                </el-button>
                <el-button plain type="primary" icon="el-icon-s-comment" @click="handleChatDialog()">聊天</el-button>
              </span>
              <span v-if="!isFollow">
                <el-button plain type="primary" @click="followUser($route.query.id)" v-if="!isFollow">
                    +关注
                </el-button>
              </span>
            </div>
          </div>
        </div>
        <el-dialog title="聊天" :visible.sync="chatDialog">
          <div class="message-container">
            <div class="message-card" v-for="(item,index) in msgList" :key="index">
              <div class="card-body" >
                <div v-if="item.isMe">
                  <img :src="item.isMe.avatar" class="avatar"/>:
                  <span class="msg">{{item.isMe.msg}}</span>
                </div>
                <div v-if="item.isHe">
                  <img :src="item.isHe.avatar" class="avatar"/>:
                  <span class="msg">{{item.isHe.msg}}</span>
                </div>
              </div>
            </div>
            <div class="msg-foot">
              <div class="foot1">
                <el-input v-model="chatContent" placeholder="请输入信息"></el-input>
              </div>
              <div class="foot2">
                <el-button type="success" @click="sendMessage()">发送</el-button>
              </div>
            </div>
          </div>

        </el-dialog>
        <div class="content-body">
            <el-row>
              <el-col :span="15">
                <div class="content-left">
                  <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="动态" name="first">
                      <!-- 我的动态 -->
                      <div class="answer-list-container">
                        <div class="list-body" v-for="(item, index) in likeAnswerList" :key="index">
                          <div>
                            <h3 class="answer-header" @click="toAnswerDetail(item.questionId,item.userId)">{{item.questionName}}</h3>
                              <p class="answer-body" v-html="item.answerMessage"></p>
                              <div class="answer-footer">
                                <span>
                                  <el-tag type="primary">{{item.modularName}}</el-tag>
                                </span>
                                <span>
                                  <el-button type="primary" v-show="item.like" disabled>{{item.likeCount}}&nbsp;已赞同</el-button>
                                </span>
                              </div>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="回答" name="second">
                      <div class="answer-list-container">
                        <div class="list-body" v-for="(item, index) in answerList" :key="index">
                          <div>
                            <h3 class="answer-header" @click="toAnswerDetail(item.questionId,item.userId)">{{item.questionName}}</h3>
                              <p class="answer-body" v-html="item.answerMessage"></p>
                              <div class="answer-footer">
                                <span>
                                  <el-tag type="primary">{{item.modularName}}</el-tag>
                                </span>
                                <span>

                                  <el-button type="primary" size="small" icon="el-icon-caret-top" disabled >已赞同{{item.likeCount}}</el-button>
                                </span>
                              </div>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="提问" name="third">
                      <div class="question-container" v-infinite-scroll="loadMore2" infinite-scroll-disabled="busy2" infinite-scroll-distance="1">
                        <div class="question-body" v-for="(item, index) in questionList" :key="index">
                          <h3 @click="toAnswerDetail(item.id)">{{item.questionName}}</h3>
                          <p><el-tag type="primary">{{item.modularName}}</el-tag></p>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="收藏" name="forth">
                      <div class="answer-list-container">
                        <div class="list-body" v-for="(item, index) in collectAnswerList" :key="index">
                          <div>
                            <h3 class="answer-header" @click="toAnswerDetail(item.questionId,item.userId)">{{item.questionName}}</h3>
                              <p class="answer-body" v-html="item.answerMessage"></p>
                              <div class="answer-footer">
                                <span>
                                  <el-tag type="primary">{{item.modularName}}</el-tag>
                                </span>
                                <span>
                                  <el-button type="success" v-show="item.collect" disabled>已收藏</el-button>
                                </span>
                              </div>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </el-col>
              <el-col :span="8" :offset="1">
                <div class="content-right">
                  <div class="number-board">
                    <div class="follow-num board-content">
                      <span>关注了</span>
                      <p>{{followCount}}</p>
                    </div>
                    <div class="fan-num board-content">
                      <span>粉丝</span>
                      <p>{{fanCount}}</p>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
    </div>
    <div class="toTop">
      <el-button @click="toTop" icon="el-icon-top" type="primary">回到顶部</el-button>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar'
import axios from 'axios'
export default {
  name: 'UserDetail',
  components: {
    NavBar
  },
  data () {
    return {
      isFollow: false,
      followCount: '',
      fanCount: '',
      busy2: false,
      changePassDialog: false,
      userList: [],
      likeAnswerList: [],
      collectAnswerList: [],
      questionList: [],
      answerList: [],
      activeName: 'first',
      imageUrl: '',
      userName: '',
      age: '',
      sex: '',
      userId: this.$route.query.id,
      loginId: localStorage.getItem('userId'),
      page2: 1,
      finalPage2: 1,
      chatDialog: false,
      webSocket: '',
      chatContent: '',
      chatUser: '123',
      chatMsg: '123',
      msgList: []
    }
  },
  created () {
    this.getInfo()
    this.showLike()
    this.handleWS()
  },
  beforeRouteLeave (to, from, next) {
    this.closeSocket()
    // this.webSocket.onClose(e => {
    //   console.log(e.data)
    // })
    next()
  },
  methods: {
    toTop () {
      var top = document.body.scrollTop || document.documentElement.scrollTop
      scrollBy(0, -top)
    },
    handleWS () {
      this.webSocket = new WebSocket('ws://127.0.0.1:9901/websocket/' + localStorage.getItem('userId'))

      this.webSocket.addEventListener('open', e => {
        console.log('open:', e.data)
      })
      this.webSocket.addEventListener('message', e => {
        console.log('message:', e.data)
        const jsonRes = JSON.parse(e.data)
        if (jsonRes.fromUser !== localStorage.getItem('userId')) {
          this.msgList.push({
            isHe: {
              msg: jsonRes.msg,
              user: jsonRes.fromUser,
              avatar: jsonRes.imgUrl
            }

          })
        }
        console.log(this.msgList)
      })
      this.webSocket.addEventListener('error', e => {
        console.log('error:', e.data)
      })
    },
    closeSocket () {
      this.webSocket.addEventListener('close', e => {
        console.log('close', e.data)
      })
    },
    sendMessage () {
      const formData = {
        msg: this.chatContent,
        toUser: this.userId,
        type: 1,
        fromUser: localStorage.getItem('userId'),
        createTime: new Date(),
        imgUrl: 'http://127.0.0.1:9901' + this.$store.state.user.avatar
      }
      this.webSocket.send(JSON.stringify(formData))
      this.chatContent = ''
      this.msgList.push({
        isMe: {
          msg: formData.msg,
          user: formData.fromUser,
          avatar: 'http://127.0.0.1:9901' + this.$store.state.user.avatar
        }
      })
    },
    handleChatDialog () {
      this.chatDialog = true
    },
    loadMore2 () {
      if (this.finalPage2 > this.page2) {
        this.busy2 = true
        this.page2++
        this.showMyQuestion(this.page2)
        setTimeout(() => {
        // 这里请求接口去拿数据，实际应该是调用一个请求数据的方法
          this.busy2 = false
        }, 1000)
      } else {
        this.busy2 = false
      }
    },
    toAnswerDetail (...param) {
      console.log(param)
      if (param[1]) {
        this.$router.push('/answer-detail?id=' + param[0] + '&creator=' + param[1])
      } else {
        this.$router.push('/answer-detail?id=' + param[0])
      }
      // answer_detail
    },
    handleClick (tab, e) {
      switch (tab.index) {
        case '0':
          this.showLike()
          break
        case '1':
          this.showMyAnswer()
          break
        case '2':
          this.showMyQuestion(1)
          break
        case '3':
          this.showCollect()
          break
      }
    },
    showCollect () {
      axios.get('/api/user/showUserCollect?userId=' + this.userId).then(res => {
        this.collectAnswerList = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    showLike () {
      axios.get('/api/user/showUserLike?userId=' + this.userId).then(res => {
        this.likeAnswerList = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    showMyAnswer (page) {
      axios.get('/api/answer/queryAnswerList?userId=' + this.userId).then(res => {
        const resData = res.data.data.alist
        this.answerList = resData
      }).catch(err => {
        console.log(err)
      })
    },
    showMyQuestion (page) {
      console.log('showQuestion')
      axios.get('/api/question/questionList?userId=' + this.userId + '&page=' + page).then(res => {
        const resData = res.data.data.rows
        this.finalPage1 = res.data.data.total
        this.questionList = this.questionList.concat(resData)
      }).catch(err => {
        console.log(err)
      })
    },
    followUser (id) {
      axios.get('/api/user/beFans?userId=' + id + '&fanId=' + localStorage.getItem('userId')).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.isFollow = true
      }).catch(err => {
        console.log(err)
      })
    },
    unFollowUser (id) {
      axios.get('/api/user/nobeFans?userId=' + id + '&fanId=' + localStorage.getItem('userId')).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.isFollow = false
      }).catch(err => {
        console.log(err)
      })
    },
    getInfo () {
      axios.get('/api/user/queryUser?id=' + this.userId)
        .then(res => {
          this.imageUrl = 'http://127.0.0.1:9901' + res.data.data.avatar
          this.userName = res.data.data.name
          this.age = res.data.data.age
          this.sex = res.data.data.sex
          this.isFollow = res.data.data.follow
          console.log(this.isFollow)
          this.fanCount = res.data.data.fanCount
          this.followCount = res.data.data.followCount
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.body{
  width: 100%;
  background: #f6f6f6;
  min-height: 1000px;
  height: auto;
  padding-top: 90px;
  .container {
    width: 70%;
    margin: 0 auto;
    min-height: 800px;
    height: auto;
    padding-bottom: 20px;
    // border: 1px solid #000;
    .content-head {
      width: 100%;
      height: 300px;
      box-shadow: 0 1px 3px rgba(26,26,26,.1);
      border-radius: 2px;
      background: #fff;
      .bg-head {
        width: 100%;
        height: 150px;
        background: #ccc;
      }
      .msg-head {
        width: 100%;
        height: 150px;
        .avatar-body {
          display: inline-block;
          width: 188px;
          height: 178px;
          padding: 5px;
          border-radius: 8px;
          background: #fff;
          position: relative;
          bottom: 80px;
          left: 30px;
        }
        .user-msg {
          display: inline-block;
          width: 200px;
          position: relative;
          bottom: 100px;
          left: 60px;
          .user-name {
            font-size: 24px;
            font-weight: bold;
          }
        }
        .edit-data {
          float: right;
          position: relative;
          top: 70px;
          right: 20px;
        }
      }
    }
    .content-body {
      margin-top: 20px;
      .content-left {
        padding: 10px;
        background: #fff;
        .answer-list-container {
          width: 100%;
          .list-body {
            padding: 10px;
            border-bottom: 1px solid #f0f2f7;
            width: 100%;
            .answer-header {
              cursor: pointer;
            }
            .answer-body {
              width: 80%;
              height: auto;
              line-height: 30px;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              // white-space: nowrap;
            }
            .answer-footer span{
              margin-right: 3%;
            }
          }
        }
        .question-container {
          .question-body {
            padding: 10px;
            border-bottom: 1px solid #f0f2f7;
            width: 100%;
            h3{
              cursor: pointer;
            }
          }
        }
        .follow-container {
          width: 100%;
          .follow-body {
            width: 100%;
            // padding: 7px;
            height: 60px;
            border-bottom: 1px solid #f0f2f7;
            line-height: 50px;
            .user-avatar {
              width: 50px;
              height: 50px;
              border-radius: 50%;
              display: inline-block;
              border: 1px solid #efefef;
            }
            .user-name {
              width: 100px;
              display: inline-block;
            }
            .user-btn {
              width: 200px;
              text-align: end;
              display: inline-block;
              position: relative;
              left: 40%;

            }
          }
        }
      }
      .content-right {
        width: 100%;
        .number-board {
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #fff;
          height: 100px;
          padding-top: 20px;
          .follow-num {
            border-right: 2px #efefef solid;
          }
          .board-content {
            width: 50%;
            text-align: center;
            line-height: 10px;
            span {
              color: #8590a6;
            }
            p {
              font-size: 20px;
              font-weight: bold;
            }
          }

        }
      }
      .edit-content {
        background: #fff;
        padding: 10px;
        width: 100%;
        .el-form {
          width: 50%;
          margin: 0 auto;
        }
        .el-input {
          width: 400px;
        }
        .btn-group {
          .el-button {
            width: 100px;
          }
        }
      }
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 3px;
}
.toTop {
  position: fixed;
  bottom: 10px;
  right: 20px;
}
.message-container {
  width: 100%;
  min-height: 500px;
  position: relative;
  .message-card {
    height: auto;
    line-height: 60px;
    padding: 5px;
    border-bottom: 1px solid #efefef;
    .card-body {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 4px;
        display: inline-block;
        vertical-align: top;
      }
      .msg {
        padding: 5px;
        color: #fff;
        font-size: 16px;
        border-radius: 4px;
        margin-left: 10px;
        background: #62b900;
      }
    }
  }
  .msg-foot {
    position: absolute;
    bottom: 0;
    display: flex;
    width: 100%;
    .foot1{
      width: 80%;
    }
    .foot2{
      margin-left: 5%;
      width: 10%;
    }
  }
}
</style>
